package com.zjdiepu.www.biz.dz;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.dao.base.DpBaseDealerInfoMapper;
import com.zjdiepu.www.dao.cw.CwIncomeExpensesItemMapper;
import com.zjdiepu.www.dao.cw.CwIncomeExpensesMapper;
import com.zjdiepu.www.dao.dh.DhRemindLoanMapper;
import com.zjdiepu.www.dao.dz.DzLendingImportBatchMapper;
import com.zjdiepu.www.dao.dz.DzLendingImportListMapper;
import com.zjdiepu.www.dao.dz.DzLendingMapper;
import com.zjdiepu.www.dao.system.BaseBusiUnitMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.dz.IDzLendingImportListService;
import com.zjdiepu.www.model.base.dto.DpBaseDealerInfo;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.cw.dto.CwIncomeExpenses;
import com.zjdiepu.www.model.cw.dto.CwIncomeExpensesItem;
import com.zjdiepu.www.model.cw.ext.CwIncomeExpensesItemExt;
import com.zjdiepu.www.model.dh.dto.DhRemindLoan;
import com.zjdiepu.www.model.dz.dto.DzLending;
import com.zjdiepu.www.model.dz.dto.DzLendingImportBatch;
import com.zjdiepu.www.model.dz.dto.DzLendingImportList;
import com.zjdiepu.www.model.dz.ext.DzLendingImportListExt;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.yw.dto.YwBusiness;

/**
 * 银行放款批量导入信息Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年08月30日 14时09分<br/>
 * @since 1.0<br/>
 */
@Service
public class DzLendingImportListServiceImpl extends BaseService implements IDzLendingImportListService {
	public static final Logger logger = LoggerFactory.getLogger(DzLendingImportListServiceImpl.class);

	@Autowired
	private DzLendingImportListMapper dzLendingImportListMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private DpBaseDealerInfoMapper dpBaseDealerInfoMapper;
	@Autowired
	private DzLendingMapper dzLendingMapper;
	@Autowired
	private DzLendingImportBatchMapper dzLendingImportBatchMapper;
	@Autowired
	private DhRemindLoanMapper dhRemindLoanMapper;
	@Autowired
	private CwIncomeExpensesMapper cwIncomeExpensesMapper;
	@Autowired
	private BaseSalersmanMapper baseSalersmanMapper;
	@Autowired
	private BaseBusiUnitMapper baseBusiUnitMapper;
	@Autowired
	private CwIncomeExpensesItemMapper cwIncomeExpensesItemMapper;
	@Autowired
	private RedisObjectClient redisObjectClient;
	@Autowired
	private YwBusinessVoMapper ywBusinessVoMapper;
	
	@Override
	public void saveImportGoods(List<DzLendingImportList> dzLendingImportList, String uuidKey, String bankCode, String bankName, AbstractSysUser currentUser) {
		
		if(CollectionUtils.isNotEmpty(dzLendingImportList)) {
			Date now = new Date();
			List<DhRemindLoan> dhRemindLoans = CollectionInitUtil.emptyList();
			List<DzLending> dzLendings = CollectionInitUtil.emptyList();
			List<CwIncomeExpenses> cwIncomeExpenses = CollectionInitUtil.emptyList();
			List<CwIncomeExpensesItem> cwIncomeExpensesItems = CollectionInitUtil.emptyList();
			redisObjectClient.execute(new RedisCallback<Boolean>() {

				@Override
				public Boolean doInRedis(RedisConnection redisConnection)
						throws DataAccessException {
						for(DzLendingImportList dzLendingImport : dzLendingImportList) {
							dzLendingImport.setBankName(bankName);
							
							String busiId = dzLendingImport.getBusiId();
							String cusId = dzLendingImport.getCusId();
							
							YwBusiness ywBusiness = new YwBusiness();
							ywBusiness.setId(busiId);
							ywBusiness.setBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());
							ywBusiness.setTimeLending(dzLendingImport.getTimeLending());
							ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
							
							ywBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
							ywBusinessVoMapper.mapper(redisConnection, ywBusiness);
							
							//插入放款还款提醒表
							DhRemindLoan dhRemindLoan = new DhRemindLoan();
							dhRemindLoan.initInsertData(currentUser.getId(), currentUser.getName());
							dhRemindLoan.setBusiId(busiId);
							dhRemindLoan.setCusId(ywBusiness.getCustomerId());
							dhRemindLoan.setTimeLending(dzLendingImport.getTimeLending());
							dhRemindLoan.setCusName(ywBusiness.getCustomerName());
							dhRemindLoan.setCusIdno(ywBusiness.getCustomerNo());
							dhRemindLoan.setLoanAmount(ywBusiness.getRealLoanAmount());
							dhRemindLoan.setChannelTypeName(ywBusiness.getChannelTypeDisplay());
							dhRemindLoan.setBankname(ywBusiness.getBankLoanDisplay());
							
							//查询经销商
							String dealerId = ywBusiness.getDealerId();
							if(StringUtils.isNotBlank(dealerId)) {
								DpBaseDealerInfo dpBaseDealerInfo = dpBaseDealerInfoMapper.selectByPrimaryKey(dealerId);
								dhRemindLoan.setDealer(dpBaseDealerInfo.getDealerName());
								String dealerLevel = dpBaseDealerInfo.getDealerLevel();
								SimpleDataDictionary dealerLevelData = redisObjectClient.hGet(SimpleDataDictionary.class.getSimpleName(), dealerLevel, DataDicType.DEALER_LEVEL.getCode());
								dhRemindLoan.setDealerLevel(dealerLevelData == null ? null : dealerLevelData.getName());
							}
							String salesmanId = ywBusiness.getSalesmanId();
							if(StringUtils.isNotBlank(salesmanId)) {
								BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salesmanId);
								if(null != baseSalersman) {
									dhRemindLoan.setSalersmanName(baseSalersman.getName());
									String unitId = baseSalersman.getUnitId();
									if(StringUtils.isNotBlank(unitId)) {
										BaseBusiUnit baseBusiUnit = baseBusiUnitMapper.selectByPrimaryKey(unitId);
										if(null != baseBusiUnit) {
											dhRemindLoan.setDepartmentName(baseBusiUnit.getOrgName());
										}
									}
								}
							}
							dhRemindLoans.add(dhRemindLoan);
							
							DzLending dzLending = new DzLending();
							dzLending.setBusiId(busiId);
							dzLending.setDpStatus(DpStatus.NORMAL.getCode());
							dzLending = dzLendingMapper.selectRefined(dzLending);
							DzLending dzLending_;
							boolean hasLending = false;
							if(dzLending == null) {
								dzLending_ = new DzLending();
								dzLending_.initInsertData(currentUser.getId(), currentUser.getName());
							} else {
								hasLending = true;
								dzLending_ = dzLending;
								dzLending_.initUpdateData(currentUser.getId(), currentUser.getName());
							}
							dzLending_.setBusiId(busiId);
							dzLending_.setCusId(cusId);
							dzLending_.setTimeLending(dzLendingImport.getTimeLending());
							dzLending_.setAmountLending(dzLendingImport.getAmountLending());
							dzLending_.setFeeService(dzLendingImport.getFeeService() == null ? 0.0 : dzLendingImport.getFeeService());
							dzLending_.setAmountLoaning(dzLendingImport.getAmountLoaning() == null ? 0.0 : dzLendingImport.getAmountLoaning());
							dzLending_.setRemarks("批量导入（"+DateUtil.dateTo8String3(now)+"）");
							if(hasLending) {
								dzLendingMapper.updateByPrimaryKeySelective(dzLending_);
							} else {
								dzLendings.add(dzLending_);
							}
							
							Double feeService = dzLendingImport.getFeeService();
							if(feeService != null && feeService > 0) {
								CwIncomeExpensesItemExt cwIncomeExpensesItemExt = new CwIncomeExpensesItemExt();
								cwIncomeExpensesItemExt.setBaseWhere();
								cwIncomeExpensesItemExt.withOutPage();
								cwIncomeExpensesItemExt.setBusiId(busiId);
								cwIncomeExpensesItemExt.setItemCode("01");
								List<CwIncomeExpensesItem> cwIncomeExpensesItems_ = cwIncomeExpensesItemMapper.selectByExt(cwIncomeExpensesItemExt);
								if(CollectionUtils.isNotEmpty(cwIncomeExpensesItems_)) {
									for(CwIncomeExpensesItem cwIncomeExpensesItem_ : cwIncomeExpensesItems_) {
										cwIncomeExpensesItem_.initUpdateData(currentUser.getId(), currentUser.getName());
										cwIncomeExpensesItem_.setDateItem(dzLendingImport.getTimeLending());
										cwIncomeExpensesItem_.setAmountItem(feeService);
										cwIncomeExpensesItem_.setRemarks("批量导入（"+DateUtil.dateTo8String3(now)+"）");
										cwIncomeExpensesItemMapper.updateByPrimaryKeySelective(cwIncomeExpensesItem_);
									}
								} else {
									CwIncomeExpenses cwIncomeExpenses_ = new CwIncomeExpenses();
									cwIncomeExpenses_.setBusiId(busiId);
									cwIncomeExpenses_.setDpStatus(DpStatus.NORMAL.getCode());
									cwIncomeExpenses_ = cwIncomeExpensesMapper.selectRefined(cwIncomeExpenses_);
									if(null == cwIncomeExpenses_) {
										cwIncomeExpenses_ = new CwIncomeExpenses();
										cwIncomeExpenses_.initInsertData(currentUser.getId(), currentUser.getName());
										cwIncomeExpenses_.setBusiId(busiId);
										cwIncomeExpenses_.setCusId(cusId);
										cwIncomeExpenses.add(cwIncomeExpenses_);
									}

									CwIncomeExpensesItem cwIncomeExpensesItem_ = new CwIncomeExpensesItem();
									cwIncomeExpensesItem_.initInsertData(currentUser.getId(), currentUser.getName());
									cwIncomeExpensesItem_.setBusiId(busiId);
									cwIncomeExpensesItem_.setCusId(cusId);
									cwIncomeExpensesItem_.setParentId(cwIncomeExpenses_.getId());
									cwIncomeExpensesItem_.setItemCode("01"); //按揭服务费
									cwIncomeExpensesItem_.setDateItem(dzLendingImport.getTimeLending());
									cwIncomeExpensesItem_.setItemDirection("01"); //收入
									cwIncomeExpensesItem_.setAmountItem(feeService);
									cwIncomeExpensesItem_.setTypeRemit("06"); 
									cwIncomeExpensesItem_.setRemarks("批量导入（"+DateUtil.dateTo8String3(now)+"）");
									cwIncomeExpensesItems.add(cwIncomeExpensesItem_);
								}
							}
						}
					return true;
				}
			});
			
			dzLendingImportListMapper.insertBatch(dzLendingImportList);
			
			if(CollectionUtils.isNotEmpty(dhRemindLoans)) {
				dhRemindLoanMapper.insertBatch(dhRemindLoans);
			}
			
			if(CollectionUtils.isNotEmpty(dzLendings)) {
				dzLendingMapper.insertBatch(dzLendings);
			}
			
			if(CollectionUtils.isNotEmpty(cwIncomeExpenses)) {
				cwIncomeExpensesMapper.insertBatch(cwIncomeExpenses);
			}
			
			if(CollectionUtils.isNotEmpty(cwIncomeExpensesItems)) {
				cwIncomeExpensesItemMapper.insertBatch(cwIncomeExpensesItems);
			}
			
			DzLendingImportBatch dzLendingImportBatch = new DzLendingImportBatch();
			dzLendingImportBatch.initInsertData(currentUser.getId(), currentUser.getName());
			dzLendingImportBatch.setId(uuidKey);
			dzLendingImportBatch.setBank(bankCode);
			dzLendingImportBatch.setBankName(bankName);
			dzLendingImportBatch.setDateReceipt(now);
			dzLendingImportBatch.setNumReceipt(dzLendingImportList.size());
			dzLendingImportBatchMapper.insert(dzLendingImportBatch);
		}
	}
	
	@Override
	public void saveUpdateAndDelete(DzLendingImportList dzLendingImportList, OperateType operType) {
		switch (operType) {
		case add:
			dzLendingImportList.initInsertData(dzLendingImportList.getModifier(), dzLendingImportList.getModifierName());
			dzLendingImportListMapper.insert(dzLendingImportList);
			break;
		case edit:
			dzLendingImportList.initUpdateData(dzLendingImportList.getModifier(), dzLendingImportList.getModifierName());
			// 影响的记录数
			int updateCount = dzLendingImportListMapper.updateByPrimaryKeySelective(dzLendingImportList);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dzLendingImportList.initDeleteData(dzLendingImportList.getModifier(), dzLendingImportList.getModifierName());
			// 影响的记录数
			int deleteCount = dzLendingImportListMapper.updateByPrimaryKeySelective(dzLendingImportList);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<DzLendingImportList> selectByExt(DzLendingImportListExt dzLendingImportListExt) {
		return dzLendingImportListMapper.selectByExt(dzLendingImportListExt);
	}
	
	@Override
	public int countByExt(DzLendingImportListExt dzLendingImportListExt){
		return dzLendingImportListMapper.countByExt(dzLendingImportListExt);
	}
	
	@Override
	public DzLendingImportList selectById(String id) {
		return dzLendingImportListMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dzLendingImportListMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DzLendingImportList dzLendingImportList) {
		return dzLendingImportListMapper.countRefined(dzLendingImportList);
	}

	@Override
	public DzLendingImportList selectRefined(DzLendingImportList dzLendingImportList) {
		return dzLendingImportListMapper.selectRefined(dzLendingImportList);
	}
	
	@Override
	public int deletedRefined(DzLendingImportList dzLendingImportList) {
		return dzLendingImportListMapper.deletedRefined(dzLendingImportList);
	}

	@Override
	public boolean repeat(DzLendingImportList dzLendingImportList) {
		int count = countRefined(dzLendingImportList);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dzLendingImportList.getId())) {
			return true;
		}
		DzLendingImportList dbItem = selectRefined(dzLendingImportList);
		if(null == dbItem) {
			return false;
		}
		return !dzLendingImportList.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dzLendingImportListMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<DzLendingImportList> dzLendingImportLists) {
		return dzLendingImportListMapper.insertBatch(dzLendingImportLists);
	}
}
